#pragma once
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <unistd.h>
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <cstring>
#include "log.hpp"

namespace Muduo
{
#define MAX_LISTEN 1024
    class Socket
    {
    public:
        Socket():_sockfd(-1){}
        Socket(int fd):_sockfd(fd){}

        ~Socket() {Close();}

        int Fd() {return _sockfd;}

        //创建套接字
        bool Create()
        {
            // #include <sys/types.h>          /* See NOTES */
            // #include <sys/socket.h>
            // int socket(int domain, int type, int protocol);
            _sockfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
            if(_sockfd<0)
            {
                ELOG("create socket error!");
                return false;
            }
            return true;
        }

        //绑定地址信息
        bool Bind(const std::string & ip,uint16_t port)
        {
            // struct sockaddr {
            //     sa_family_t sa_family;
            //     char        sa_data[14];
            // }
            // int bind(int sockfd, const struct sockaddr *addr,socklen_t addrlen);
            struct sockaddr_in addr;//struct sockaddr_in 是 struct sockaddr 的一个具体实现，专门用于表示IPv4地址
            addr.sin_family = AF_INET;
            addr.sin_port = htons(port);
            addr.sin_addr.s_addr = inet_addr(ip.c_str());
            socklen_t len = sizeof(struct sockaddr_in);
            int ret = bind(_sockfd,(struct sockaddr*)&addr,len);
            if(ret<0)
            {
                ELOG("bind address error!");
                return false;
            }
            return true;
        }

        //开始监听
        bool Listen(int backlog = MAX_LISTEN) //最大监听数量
        {
            //int listen(int sockfd, int backlog);
            int ret = listen(_sockfd,backlog);
            if(ret<0)
            {
                ELOG("socket listen error!");
                return false;
            }
            return true;
        }

        //向服务器发起连接
        bool Connect(const std::string & ip,uint16_t port)
        {
            // int connect(int sockfd, const struct sockaddr *addr,socklen_t addrlen);
            // #include <sys/socket.h>
            // #include <netinet/in.h>
            // #include <arpa/inet.h>
            // in_addr_t inet_addr(const char *cp);
            struct sockaddr_in addr;
            addr.sin_family = AF_INET;
            addr.sin_port = htons(port);
            addr.sin_addr.s_addr = inet_addr(ip.c_str());
            socklen_t len = sizeof(struct sockaddr_in);
            int ret = connect(_sockfd,(struct sockaddr*)&addr,len);
            if(ret<0)
            {
                ELOG("connect server error!");
                return false;
            }
            return true;
        }

        //获取新链接
        int Accept()
        {
            // int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
            //不用记录客户端信息
            int newfd = accept(_sockfd,nullptr,nullptr);
            if(newfd<0)
            {
                ELOG("socket accept error! errno: %d, %s", errno, strerror(errno));
                return -1;
            }
            return newfd;
        }

        //接收数据
        ssize_t Recv(void * buf,size_t len,int flag = 0)
        {
            //ssize_t recv(int sockfd, void *buf, size_t len, int flags);
            ssize_t ret = recv(_sockfd,buf,len,flag);
            if(ret<=0)
            {
                //EAGAIN当前socket接收缓冲区没有数据,处于非阻塞情况下出现
                //EINTR表示当前socket阻塞,被信号中断了
                if(errno == EAGAIN||errno == EINTR)
                {
                    return 0;//这次没有接收到数据
                }
                ELOG("socket recv error!");
                return -1;
            }
            return ret;//实际接收的数据长度
        }

        //以非阻塞接收数据
        ssize_t NonBlockRecv(void * buf,size_t len)
        {
            return Recv(buf,len,MSG_DONTWAIT);//以非阻塞方式读取数据
        }

        //发送数据
        ssize_t Send(const void * buf,size_t len,int flag = 0)
        {
            //ssize_t send(int sockfd, const void *buf, size_t len, int flags);
            ssize_t ret = send(_sockfd,buf,len,flag);
            if(ret<0)
            {
                if(errno==EAGAIN||errno == EINTR)
                {
                    return 0;
                }
                ELOG("socket send error!");
                return -1;
            }
            return ret;//返回实际发送的数据长度
        }

        //以非阻塞的方式发送数据
        ssize_t NonBlockSend(void * buf,size_t len)
        {
            if(len == 0) return 0;
            return Send(buf,len,MSG_DONTWAIT);
        }

        //关闭套接字
        void Close()
        {
            if(_sockfd != -1)
            {
                close(_sockfd);
                _sockfd = -1;
            }
        }

        //创建一个服务端连接
        bool CreateServer(uint16_t port,const std::string & ip = "0.0.0.0",bool block_flag = false)
        {
            //创建套接字->启动地址重用->设置非阻塞->绑定地址->开始监听
            if(Create() == false) return false;
            ReuseAddress();
            if(block_flag) NonBlock();
            if(Bind(ip,port)==false) return false;
            if(Listen() == false) return false;  
            return true;
        }

        //创建一个客户端连接
        bool CreateClient(uint16_t port,const std::string &ip)
        {
            //创建套接字->指定连接的服务器
            if(Create() == false) return false;
            if(Connect(ip,port) == false) return false;
            return true;
        }

        //设置套接字->开启地址端口重用
        void ReuseAddress()
        {
            // int setsockopt(int sockfd, int level, int optname,const void *optval, socklen_t optlen);
            int val = 1;
            setsockopt(_sockfd,SOL_SOCKET,SO_REUSEADDR,(void*)&val,sizeof(val));
            val = 1;
            setsockopt(_sockfd,SOL_SOCKET,SO_REUSEPORT,(void*)&val,sizeof(val));
        }

        //设置套接字阻塞属性->设置为非阻塞
        void NonBlock()
        {
            //int fcntl(int fd, int cmd, ... /* arg */ );
            int flag = fcntl(_sockfd,F_GETFL,0);
            fcntl(_sockfd,F_SETFL,flag|O_NONBLOCK);
        }

    private:
        int _sockfd;//监听套接字
    };
}